package edu.clarkson.ee368.spring2012.coreservices;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
public class ApplicationServiceBean implements ApplicationService {
	
	@PersistenceContext
	private EntityManager em;
	
	private MessageDigest md;
	
	public ApplicationServiceBean() {
		try {
			this.md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public String createApplication(String company, String applicationName) {
		HostedApplication application = new HostedApplicationImpl();
		application.setCompany(company);
		application.setApplicationName(applicationName);
		application.setVersion(1);
		
		String data = company + "-" + applicationName + "-" + "1" + new Date().toString();
		md.update(data.getBytes());
		String md5 = new String(md.digest());
		application.setAplicationSecret(md5);
		em.persist(application);
		em.flush();
		return md5;
		
		
	}

	@Override
	public HostedApplication getApplication(String applicationSecret) {
		return (HostedApplication) em.find(HostedApplicationImpl.class, applicationSecret);
	}

	@Override
	public void updateApplication(HostedApplication application) {
		em.flush();
	}

}
